<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'
//@ts-ignore
// import startPreview from "@/components/preview.vue";
//@ts-ignore
import template from "./template.js"
//@ts-ignore
import { hiprint } from "vue-plugin-hiprint";
//@ts-ignore
import { newHiprintPrintTemplate } from "@/utils/template-helper";
//@ts-ignore
import $ from "jquery";

import useqdprint from '@/hooks/sign_bill/qd_print.js'
//@ts-ignore
import { throttle } from 'lodash';

import { useSignStore } from '@/store/sign';

let loadshow = ref(false)
const signStore = useSignStore();

const {
    getTableData,
    getPrintData,
    printData,
    printTime
} = useqdprint()




const TEMPLATE_KEY = getCurrentInstance()?.type.name; // 存储模板对象的 key
const checked1 = ref(false)
let cid = ref('')
let con = ref('')

// ref 创建的模板json
const templateRef = ref(template);
// const preview: any = ref(null);

onMounted(() => {
    buildDesigner();
    getHtml('', '');
});

/**
 * 构建设计器
 * 注意: 必须要在 onMounted 中去构建
 * 因为都是把元素挂载到对应容器中, 必须要先找到该容器
 */
let hiprintTemplate: any;

const buildDesigner = async () => {
    $("#hiprint-printTemplate").empty(); // 先清空, 避免重复构建
    hiprintTemplate = newHiprintPrintTemplate(TEMPLATE_KEY, {
        template: templateRef.value, // 模板json(object)
        settingContainer: "#PrintElementOptionSetting", // 元素参数容器
    });
    // 构建 并填充到 容器中
    hiprintTemplate.design("#hiprint-printTemplate");
};

/**
 * 直接打印: 借助客户端,静默打印(无弹窗直接打印)
 * 注意: 需要先连接客户端
 */
const print2 = async (checked1: any, row: any) => {
    await getPrintData(checked1, row);
    // 先判断printData是不是undefined, 因为可能是空数组, 导致后面调用打印方法报错

    if (printData.table.length === 0) {
        alert("没有数据");
        return;
    }
    if (hiprint.hiwebSocket.opened) {
        hiprintTemplate.print2(printData);
        hiprintTemplate.on("printSuccess", async function (_e: any) {
            try {
                let res = await printTime(row.Con_PickingID);
                if (res === 'ok') {
                    signStore.refreshData_pinia = signStore.refreshData_pinia.filter((item: any) => item.Con_PickingID !== row.Con_PickingID);
                    showModal("已打印");
                }
            } catch (e) {
                alert("数据库更新失败");
            }
        })
        hiprintTemplate.on("printError", function (e: any) {
            alert("直接打印失败"+e);
        });

    } else {
        alert("请先连接客户端(刷新网页), 然后再点击「直接打印」");
    }
};

function showModal(...html: any) {
    do {
        $(".container").empty();
        $(".container").html(html);
        if ($(".container").length > 0) {
            return;
        }

    } while ($(".container").length <= 0);
}
const getHtml = async (checked1: any, row: any) => {
    try {
        loadshow.value = true;
        let res = await getPrintData(checked1, row);
        if (res !== 'ok') {
            showModal("没有数据");
            return;
        }
        // let html = hiprintTemplate.getHtml(printData);
        let html = hiprintTemplate.getHtml(printData);
        // // 将html字符串转换为DOM元素
        // const tempDiv = document.createElement('div');
        // tempDiv.innerHTML = html[0].innerHTML;

        // // 找到所有的td元素
        // const tds = tempDiv.querySelectorAll('td');

        // // 遍历每个td元素，修改style属性
        // tds.forEach(td => {
        //     // 检查是否已有style属性
        //     if (td.hasAttribute('style')) {
        //         // 追加font-weight: 700;到现有的style后面
        //         td.style.cssText += ' font-weight: 700;';
        //     } else {
        //         // 如果没有style属性，直接设置
        //         td.setAttribute('style', 'font-weight: 700;');
        //     }
        // });

        // // 将修改后的内容赋值回去
        // html[0].innerHTML = tempDiv.innerHTML;
        showModal(html);
    } catch (e) {
        alert("获取数据失败");
    } finally {
        loadshow.value = false;
    }
};

// 刷新 节流函数
const throttleRefresh = throttle((cid: string, con: string) => getTableData(cid, con), 3000, {
    leading: true, // 第一次触发立即执行
    trailing: false // 最后一次触发不执行
});
// 预览 节流函数
const throttlePreview = throttle((checked1: any, row: any) => getHtml(checked1, row), 1000, {
    leading: true, // 第一次触发立即执行
    trailing: false // 最后一次触发不执行
});
// 打印 节流函数
const throttlePrint = throttle((checked1: any, row: any) => print2(checked1, row), 2000, {
    leading: true, // 第一次触发立即执行
    trailing: false // 最后一次触发不执行
});


</script>

<template>
    <el-card>
        <el-form @submit.native.prevent class="form">
            <el-form-item>
                <el-checkbox v-model="checked1" label="自制件" size="large" />
                <el-button type="primary" @click="throttleRefresh(cid, con)" v-has="`btn_sign_refresh`"
                    style="margin-left: 15px;">刷新</el-button>
            </el-form-item>

            <el-form-item label="识别码查询:">
                <el-input v-model="cid" placeholder="请输入识别码"></el-input>
            </el-form-item>
            <el-form-item label="合同号查询:">
                <el-input v-model="con" placeholder="请输入合同号"></el-input>
            </el-form-item>
        </el-form>
    </el-card>

    <el-card>
        <section class="table-card">
            <div class="table-card-left">
                <el-scrollbar style="height: calc(100vh - 300px);"> <!-- 菜单滚动条 -->
                    <el-table :data="signStore.refreshData_pinia" style="width: 100%">
                        <el-table-column prop="ContractNO" label="合同号" width="100"></el-table-column>
                        <el-table-column prop="Con_PickingID" label="识别码" width="100"></el-table-column>
                        <el-table-column prop="Classify" label="仓库" width="60"></el-table-column>
                        <el-table-column prop="Warehouse" label="楼栋" width="130"></el-table-column>
                        <el-table-column prop="Position" label="货位" width="80"></el-table-column>
                        <el-table-column prop="LotNoDate" label="派发日期" width="110"></el-table-column>
                        <el-table-column prop="LotNo" label="波次" width="60"></el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="small" type="success" @click="throttlePreview(checked1, scope.row)"
                                    v-has="`btn_sign_preview`">预览</el-button>
                                <el-button size="small" type="danger" @click="throttlePrint(checked1, scope.row)"
                                    v-has="`btn_sign_print`">打印</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-scrollbar>
            </div>
            <div class="table-card-right">
                <div class="spinner" v-if="loadshow">
                    <div class="spinnerin"></div>
                </div>
                <el-scrollbar style="height: calc(100vh - 300px);"> <!-- 菜单滚动条 -->
                    <!-- <start-preview ref="preview" /> -->
                    <div class="modal">
                        <div class="container"></div>
                    </div>
                </el-scrollbar>
            </div>
        </section>
    </el-card>
</template>


<style scoped lang="scss">
.table-card {
    display: flex;

    .table-card-left {
        flex: 1;
    }

    .table-card-right {
        flex: 1;
    }
}

.form {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 不同模板 间隙 */
.container .hiprint-printTemplate {
    background: #fff;
    border-bottom: 10px solid #ccc;
}

/* 批量打印 间隙 */
.container .hiprint-printTemplate .hiprint-printPanel:not(:last-of-type) {
    border-bottom: 5px solid #ccc;
}

.spinner {
    width: 3em;
    height: 3em;
    position: absolute;
    top: 50%;
    left: 50%;

    //最顶层
    z-index: 9999;
    cursor: not-allowed;
    border-radius: 50%;
    border: 2px solid #444;
    box-shadow: -10px -10px 10px #6359f8, 0px -10px 10px 0px #9c32e2, 10px -10px 10px #f36896, 10px 0 10px #ff0b0b, 10px 10px 10px 0px#ff5500, 0 10px 10px 0px #ff9500, -10px 10px 10px 0px #ffb700;
    animation: rot55 0.7s linear infinite;
}

.spinnerin {
    border: 2px solid #444;
    width: 1.5em;
    height: 1.5em;
    border-radius: 50%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

@keyframes rot55 {
    to {
        transform: rotate(360deg);
    }
}
</style>